Array.prototype.contains = function (ele) {
    for (var i = 0; i < this.length; i++) {
        if (this[i] == ele) {
            return true;
        }
    }
    return false;
}

// 更新配置
var config = {};
var dragConfig = {};
var loaded = false;
var updateConfig = function () {
    if (!loaded) {
        chrome.runtime.sendMessage({ type: "evt_getconf" }, function (response) {
            if (response) {
                // 所有配置
                config = response.config;
                loaded = config.loaded;
                // 拖拽配置
                dragConfig = response.config["drag"];
                // 手势配置
                if (config.mges.settings.fnmges) {
                    gesture.initConfig();
                }
            }
            superdrag.init();
            gesture.init();
        });
    }
}
// shoushidaima
var editMode, editDirect;
var gesture = {
    init: function () {
        gesture.initHandle();
    },
    initConfig: function () {
        gesture.uistyle = {};
        gesture.uistyle.mges = [];
        var _uimges = ["direct", "tip", "note"];
        for (var i = 0; i < _uimges.length; i++) {
            if (config.mges.ui[_uimges[i]].enable) {
                gesture.uistyle.mges.push(config.mges.ui[_uimges[i]].style);
            } else {
                gesture.uistyle.mges.push("none");
            }
        }
    },
    initHandle: function () {
        document.addEventListener("mousedown", this, false);
        document.addEventListener("mouseup", this, false);
        document.addEventListener("mousemove", this, false);
        document.addEventListener("mouseover", this, false);
        document.addEventListener("contextmenu", this, false);
        window.addEventListener("keydown", this, false);
    },
    initHandle2: function () {
        gesture.document.addEventListener("mouseup", this, false);
        gesture.document.addEventListener("mousemove", this, false);
        gesture.document.addEventListener("mouseover", this, false);
        gesture.document.addEventListener("contextmenu", this, false);
    },
    handleEvent: function (e) {
        switch (e.type) {
            case "keydown":
                if (!config.mges.settings.fnmges) {
                    break;
                }
                if (e.keyCode == 27) {
                    gesture.break = true;
                    gesture.stopMges(e);
                    gesture.timeout_nomenu = true;
                }
                break;
            case "mousedown":
                // 点击右键时更新一下配置信息
                updateConfig();
                if (!config.mges.settings.fnmges) {
                    break;
                }
                if (e.button == config.mges.settings.model
					&& !e[config.mges.settings.holdkey + "Key"]) {    
                    gesture.lineDrawReady(e, "mges");
                }
                break;
            case "mouseup":
                if (!config.mges.settings.fnmges) {
                    break;
                }
                if (e.button == config.mges.settings.model && gesture.actionMges) {
                    gesture.doMges(e);
                    gesture.actionMges = false;
                }
                break;
            case "contextmenu":
                if (!config.mges.settings.fnmges) {
                    break;
                }
                if (gesture._dirArray && gesture.drawing) {
                    gesture.stopMges(e);
                }
                if (gesture.drawing && config.mges.settings.model == 2) {
                    gesture.clearUI();
                    gesture.drawing = false;
                    gesture._lastX = e.clientX;
                    gesture._lastY = e.clientY;
                }
                if (config.mges.settings.timeout_nomenu && gesture.timeout_nomenu) {
                    gesture.timeout_nomenu = false;
                    e.preventDefault();
                }
                break;
            case "mousemove":
                updateConfig();
                if (!config.mges.settings.fnmges) {
                    break;
                }
                if (gesture.drawing && e.button == config.mges.settings.model) {
                    gesture.lineDraw(e);
                }
                break;
        }
    },
    lineDrawReady: function (e, type) {
        gesture._lastX = e.clientX;
        gesture._lastY = e.clientY;
        gesture._startX = e.clientX;
        gesture._startY = e.clientY;

        gesture._dirArray = "";
        gesture.drawing = true;
        gesture.actionMges = true;
        if (type == "mges") {
            gesture.drawType = ["mges", "mges"];
        }

        gesture.selEle = {};
        gesture.selEle.txt = window.getSelection().toString();
        gesture.selEle.lnk = e.href || e.target.href;
        gesture.selEle.img = e.target.src;
        gesture.selEle.str = e.target.innerText;
        gesture.startEle = e.target;

        var ele = e.target;
        var getParent = function (win) {
            if (win.parent && win.parent != win) {
                return arguments.callee(win.parent);
            } else {
                return win
            }
        }
        gesture.window = getParent(window);
        gesture.document = window.document.documentElement;
        gesture.initHandle2();

        var _uiarray = ["direct", "tip", "note", "allaction"];
        var _uiset = [];
        for (var i = 0; i < _uiarray.length; i++) {
            if (config["mges"].ui && config["mges"].ui[_uiarray[i]].enable) {
                gesture.UI(config["mges"].ui[_uiarray[i]].style);
            }
        }

        return
    },
    lineDraw: function (e, type) {
        gesture.uiPos(e)

        var x = e.clientX;
        var y = e.clientY;
        var dx = Math.abs(x - gesture._lastX);
        var dy = Math.abs(y - gesture._lastY);
        var dz = Math.sqrt(Math.pow(dx, 2) + Math.pow(dy, 2));

        if (dz < 1) { return }
        config["mges"].ui.line.enable ? gesture.ui_line(e) : null;
        if (dx < config.mges.settings.minlength
			&& dy < config.mges.settings.minlength) {
            return;
        }

        var dir;
        if (dx > dy) {
            dir = x < gesture._lastX ? "L" : "R";
        } else {
            dir = y < gesture._lastY ? "U" : "D";
        }

        var lastDir = gesture._dirArray.substr(gesture._dirArray.length - 1, 1);
        if (dir != lastDir) {
            gesture._dirArray += dir;
            //show direct
            config["mges"].ui.direct.enable ? gesture.ui_direct(e) : null;
            //get tip
            (config["mges"].ui.tip.enable || config["mges"].ui.note.enable) ? gesture.sendDir(gesture._dirArray, "gettip", e) : null;
        }
        //timeout
        if (config.mges.settings.timeout) {
            if (gesture.timeout) { window.clearTimeout(gesture.timeout); gesture.break = false; }
            gesture.timeout = window.setTimeout(function () {
                gesture.break = true;
                gesture.clearUI();
            }, config.mges.settings.timeoutvalue * 1000)
        }
        gesture._lastX = e.clientX;
        gesture._lastY = e.clientY;
    },
    UI: function (style) {
        var domui = gesture.document.querySelector("div[data-suui=uibox][data-sustyle=" + style + "]");
        if (!domui) {
            domui = document.createElement("div");
            domui.dataset.suui = "uibox";
            domui.dataset.sustyle = style;
            domui.style.cssText +=
				"position:fixed;" +
				"z-index:" + parseInt((new Date()) / 1000);
            if (style == "hover") {
                domui.style.cssText += "right:-2px;bottom:0;text-align:right;"
            }
            if (style == "ui_bottom") {
                domui.style.cssText += "bottom:-2px;text-align:center;"
            }
            gesture.document.appendChild(domui)
        }
    },
    ui_line: function (e) {
        if (!gesture.document.querySelector("div[data-suui=line]")) {
            var svgdiv = this.svgdiv = document.createElement("div");
            svgdiv.dataset.suui = "line";
            svgdiv.style.cssText += "position:fixed;left:0;top:0;display:block;background:transparent;border:none;" +
                "width:" + gesture.window.innerWidth + "px;" +
                "height:" + gesture.window.innerHeight + "px;" +
                "z-index:" + parseInt((new Date().getTime()) / 1000);
            var SVG = 'http://www.w3.org/2000/svg';
            var svgtag = gesture.svgtag = document.createElementNS(SVG, "svg");
            svgtag.style.cssText += "width:" + gesture.window.innerWidth + "px;" + "height:" + gesture.window.innerHeight + "px;";
            var polyline = document.createElementNS(SVG, 'polyline');
            polyline.style.stroke = config["mges"].ui.line.color;
            polyline.style.strokeOpacity = config["mges"].ui.line.opacity;
            polyline.style.strokeWidth = config["mges"].ui.line.width;
            polyline.style.fill = "none";
            this.polyline = polyline;

            svgtag.appendChild(polyline);
            svgdiv.appendChild(svgtag);
            gesture.document.appendChild(svgdiv);
        }
        this.startX = e.clientX;
        this.startY = e.clientY;
        if (gesture.svgtag) {
            var p = gesture.svgtag.createSVGPoint();
            p.x = this.startX;
            p.y = this.startY;
            this.polyline.points.appendItem(p);
        } else {
            return
        }
    },
    ui_direct: function (e) {
        if (!config["mges"].ui.direct.enable) { return; }
        var uidom = gesture.document.querySelector("div[data-suui=uibox][data-sustyle=" + config["mges"].ui.direct.style + "]");
        var ui_dir = uidom.querySelector("div[data-suui=dir]");
        if (ui_dir) {
            var _img = document.createElement("img");
            _img.src = chrome.extension.getURL("") + "images/" + "direct.png";
            _img.style.cssText +=
                "float:left;" +
                gesture.directimg(gesture._dirArray[gesture._dirArray.length - 1]) +
                "zoom:" + Number(config["mges"].ui.direct.width) / 32;
            ui_dir.appendChild(_img)
        } else {
            ui_dir = document.createElement("div");
            ui_dir.dataset.suui = "dir";
            ui_dir.style.cssText +=
				"display:inline-block;text-align:center;border-radius:2px;padding:0 5px;" +
				"background-color:" + config["mges"].ui.direct.color + " !important;" +
				"opacity:" + config["mges"].ui.direct.opacity;
            ui_dir.appendChild(gesture.domDir2(gesture._dirArray[gesture._dirArray.length - 1]));
            uidom.appendChild(ui_dir);

            var _br = document.createElement("br");
            _br.style.cssText += "/*display:none;*/";
            uidom.appendChild(_br);
        }
    },
    ui_tip: function (confOBJ, e) {
        if (!config["mges"].ui.tip.enable) { return; }
        var uidom = gesture.document.querySelector("div[data-suui=uibox][data-sustyle=" + config["mges"].ui.tip.style + "]");
        if (!uidom) { return }
        var _dom = uidom ? uidom.querySelector("div[data-suui=tip]") : null;
        if (!_dom) {
            var _dom = document.createElement("div");
            _dom.dataset.suui = "tip";
            _dom.style.cssText +=
                "display:inline-block;padding: 8px 10px;border-radius: 3px;font-family: arial,sans-serif !important;" +
                "background-color:" + config["mges"].ui.tip.bgcolor + ";" +
                "color:" + config["mges"].ui.tip.color + ";" +
                "font-size:" + config["mges"].ui.tip.width + "px;" +
                "opacity:" + config["mges"].ui.tip.opacity + ";"
            uidom.appendChild(_dom);
            var _br = document.createElement("br");
            _br.style.cssText += "/*display:none;*/";
            uidom.appendChild(_br);
        }
        if (confOBJ.tip) {
            var domdir = gesture.domDir();
            _dom.innerHTML = (domdir + confOBJ.tip);
            _dom.style.cssText += "display:inline-block;";
        } else {
            _dom.innerHTML = "";
            _dom.style.cssText += "display:none;";
        }
    },
    ui_note: function (confOBJ, e) {
        if (!config["mges"].ui.note.enable) { return; }
        var uidom = gesture.document.querySelector("div[data-suui=uibox][data-sustyle=" + config["mges"].ui.note.style + "]");
        var _dom = uidom.querySelector("div[data-suui=note]");
        if (!_dom) {
            _dom = document.createElement("div");
            _dom.dataset.suui = "note";
            _dom.style.cssText += "font-family: arial,sans-serif !important;font-style: italic;/*position:fixed;*/" +
			"color:" + config["mges"].ui.note.color + ";" +
			"font-size:" + config["mges"].ui.note.width + "px;" +
			"opacity:" + config["mges"].ui.note.opacity + ";"
            uidom.appendChild(_dom);
            uidom.appendChild(document.createElement("br"));
        }
        if (confOBJ.note && confOBJ.note.type && confOBJ.note.value) {
            _dom.style.cssText += "display:inline-block;";
            _dom.innerText = confOBJ.note.value;
        } else {
            _dom.style.cssText += "display:none;";
            _dom.innerText = "";
            return;
        }
        return
        if (_dom && !confOBJ.note.value) {
            _dom.style.cssText += "display:none;";
            _dom.innerText = "";
            return;
        }
        if (_dom) {
            _dom.style.cssText += "display:inline-block;";
            _dom.innerText = confOBJ.note.value;
        } else {
            _dom = document.createElement("div");
            _dom.dataset.suui = "note";
            _dom.style.cssText += "font-family: arial,sans-serif !important;font-style: italic;position:fixed;" +
			"color:" + config["mges"].ui.note.color + ";" +
			"font-size:" + config["mges"].ui.note.width + "px;" +
			"opacity:" + config["mges"].ui.note.opacity + ";"
            _dom.innerText = confOBJ.note.value;
            uidom.appendChild(_dom);
            uidom.appendChild(document.createElement("br"));
        }
    },
    ui_allaction: function (confOBJ, e) {
        if (!config["mges"].ui.allaction.enable) { return; }
        var uidom = gesture.document.querySelector("div[data-suui=uibox][data-sustyle=" + config["mges"].ui.allaction.style + "]");
        var _dom = uidom.querySelector("div[data-suui=allaction]");
        if (!_dom) {
            _dom = document.createElement("div");
            _dom.dataset.suui = "allaction";
            _dom.style.cssText += "font-family: arial,sans-serif !important;text-align:left;padding: 5px 20px;border-radius: 2px;" +
			"color:" + config["mges"].ui.allaction.color + ";" +
			"background-color:" + config["mges"].ui.allaction.bgcolor + ";" +
			"font-size:" + config["mges"].ui.allaction.width + "px;" +
			"opacity:" + config["mges"].ui.allaction.opacity + ";"
            uidom.appendChild(_dom);
        } else {
            _dom.innerHTML = "";
        }
        if (confOBJ.allaction && confOBJ.allaction.length > 0) {
            for (var i = 0; i < confOBJ.allaction.length; i++) {
                var _img = "";
                for (var ii = 0; ii < confOBJ.allaction[i].direct.length; ii++) {
                    _img += "<img src='" + chrome.extension.getURL("") + "images/" + "direct.png" + "' style='float:left;" + gesture.directimg(confOBJ.allaction[i].direct[ii]) + ";zoom:" + Number(config["mges"].ui.allaction.width) / 32 + "'>"
                }
                var _acction = document.createElement("div");
                _acction.innerHTML = _img + "&nbsp;&nbsp;" + confOBJ.allaction[i].tip;
                _dom.appendChild(_acction);
            }
            _dom.style.cssText += "display:inline-block;";
        } else {
            _dom.innerHTML = "";
            _dom.style.cssText += "display:none;";
        }
    },
    directimg: function (direct) {
        var myDeg = { L: "0deg", U: "90deg", R: "180deg", D: "270deg" };
        return "-webkit-transform:rotate(+" + myDeg[direct] + ");";
    },
    domDir2: function (img) {
        var domimg = document.createElement("img");
        domimg.src = chrome.extension.getURL("") + "images/" + "direct.png";
        domimg.style.cssText +=
            "float:left;" +
            gesture.directimg(img) +
            "zoom:" + Number(config["mges"].ui.direct.width) / 32;
        return domimg;
    },
    domDir: function () {
        if (config["mges"].ui.tip.withdir) {
            var domdir = "";
            for (var i = 0; i < gesture._dirArray.length; i++) {
                domdir += "<img src='" + chrome.extension.getURL("") + "images/" + "direct.png" + "' style='float:left;margin-top:2px;" + gesture.directimg(gesture._dirArray[i]) + ";zoom:" + Number(config["mges"].ui.tip.width) / 32 + "'>"
            }
            return domdir;		
        } else {
            return "";
        }
    },
    uiPos: function (e) {
        var uibox_follow = gesture.document.querySelector("div[data-suui=uibox][data-sustyle=follow]"),
			uibox_center = gesture.document.querySelector("div[data-suui=uibox][data-sustyle=center]"),
			uibox_bottom = gesture.document.querySelector("div[data-suui=uibox][data-sustyle=ui_bottom]");
        uibox_follow ? (uibox_follow.style.cssText += "left:" + (e.clientX + 10) + "px;" + "top:" + (e.clientY + 30) + "px") : null;
        if (uibox_center) {
            var _width = window.getComputedStyle(uibox_center).width;
            _width = _width.substr(0, _width.length - 2);
            _width = (window.innerWidth - _width) / 2;
            var _height = window.getComputedStyle(uibox_center).height;
            _height = _height.substr(0, _height.length - 2);
            _height = (window.innerHeight - _height) / 2;
            uibox_center.style.cssText +=
				"left:" + _width + "px;" +
				"top:" + _height + "px;";
        }
        if (uibox_bottom) {
            var _width = window.getComputedStyle(uibox_bottom).width;
            _width = _width.substr(0, _width.length - 2);
            _width = (window.innerWidth - _width) / 2;
            var _height = window.getComputedStyle(uibox_bottom).height;
            _height = _height.substr(0, _height.length - 2);
            _height = (window.innerHeight - _height) / 2;
            uibox_bottom.style.cssText += "left:" + _width + "px;"
        }
    },
    clearUI: function () {
        gesture.document.querySelector("div[data-suui=line]") ? gesture.document.querySelector("div[data-suui=line]").remove() : null;
        var doms = gesture.document.querySelectorAll("div[data-suui=uibox]");
        for (var i = 0; i < doms.length; i++) {
            if (doms[i]) { doms[i].remove() }
        }
    },
    doMges: function (e) {
        if (gesture.break) {
            gesture.clearUI();
            gesture.drawing = false;
            gesture.break = false;
            return;
        }
        gesture.clearUI();
        if (editMode) {
            editDirect = gesture._dirArray;
            var getele = function (ele) {
                if (ele.tagName.toLowerCase() == "supergesture" && ele.classList.contains("su_apps")) {
                    return ele;
                } else {
                    return getele(ele.parentNode);
                }
            }
            var boxOBJ = getele(document.querySelector(".su_app_test"));
            boxOBJ.querySelector(".testbox").innerText = gesture._dirArray;
        } else {
            gesture.sendDir(gesture._dirArray, "action", e);
        }
    },
    stopMges: function (e) {
        if (gesture.break) {
            gesture.clearUI();
            gesture.break = false;
            gesture.drawing = false;
            return;
        }
        gesture.clearUI();
        e.preventDefault();
        gesture._dirArray = "";
        gesture.drawing = false;
    },
    sendDir: function (dir, dirType, e) {
        var returnValue;
        chrome.runtime.sendMessage({ type: dirType, direct: dir, drawType: ["mges", "mges"], selEle: gesture.selEle }, function (response) {
            returnValue = response;
            gesture.getedConf = returnValue;
            switch (response.type) {
                case "tip":
                    gesture.ui_tip(response, e);
                    gesture.ui_note(response, e);
                    gesture.ui_allaction(response, e);
                    gesture.uiPos(e);
                    break;
                case "action":
                    switch (response.typeAction) {
                        case "paste":
                            gesture.startEle.value += response.paste;
                            break;
                    }
                    break;
            }
        });
    }
}
// 拖拽代码
var superdrag = {
    in_drag: false,
    drag_selection: {
        type: "text",
        data: ""
    },
    start_x: -1,
    start_y: -1,

    init: function () {
        document.addEventListener("dragstart", this, false);
        document.addEventListener("dragover", this, false);
        document.addEventListener("drop", this, false);
        document.addEventListener("dragend", this, false);
    },

    handleEvent: function (e) {
        switch (e.type) {
            case "dragstart":
                {
                    if (dragConfig["fndrag"]) {
                        return superdrag.dragStart(e);
                    }
                    return true;
                }
            case "dragover":
                {
                    if (dragConfig["fndrag"]) {
                        return superdrag.dragOver(e);
                    }
                    return true;
                }
            case "drop":
                {
                    if (dragConfig["fndrag"]) {
                        return superdrag.drop(e);
                    }
                    return true;
                }
            case "dragend":
                {
                    if (dragConfig["fndrag"]) {
                        return superdrag.dragEnd(e);
                    }
                    return true;
                }
        }
    },

    getTextLink: function (text) {
        var re = /((http|ftp|https):\/\/|www\.)[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:\/~\+#\*!]*[\w\-\.,@?^=%&:\/~\+#\*!])?/;
        var link = "";
        var matches = text.match(re);
        if (matches) {
            link = matches[0];
        }
        return link;
    },

    getDragSelection: function (e) {
        var data;
        var data_type = "text";
        var selection = window.getSelection();
        var parent_node = e.srcElement;
        while (parent_node && parent_node.nodeName != "A") {
            parent_node = parent_node.parentNode;
        }
        if (e.srcElement.nodeName == "IMG") {
            if (parent_node) {
                if (parent_node.href.substr(0, 11) != "javascript:") {
                    data_type = "link";
                    data = parent_node.href;
                }
            } else {
                data_type = "img";
                data = e.srcElement.src;
            }
        } else {
            data = e.dataTransfer.getData('Text');
            if (!data) {
                data = selection.toString();
            }
        }
        return {
            "type": data_type,
            "data": data
        };
    },

    dragStart: function (e) {
        if (dragConfig["alt_key"] == "true" && e.altKey ||
            dragConfig["ctrl_key"] == "true" && e.ctrlKey) {
            return true;
        }
       
        this.in_drag = true;
        this.start_x = e.clientX;
        this.start_y = e.clientY;
        this.drag_selection = this.getDragSelection(e);
        if (this.drag_selection.type == "text") {
            var link = this.getTextLink(this.drag_selection.data);
            if (link != "") {
                this.drag_selection.type = "link";
                this.drag_selection.data = link;
            } else {
                return true;
            }
        }

        return false;
    },

    dragOver: function (e) {
        if (!this.in_drag) {
            return true;
        }
        
        if (e.preventDefault) {
            e.preventDefault();
        }
        e.dataTransfer.effectAllowed = "copy";
        e.dataTransfer.dropEffect = "copy";
        return false;
    },

    drop: function (e) {
        if (!this.in_drag) {
            return true;
        }
        this.in_drag = false;
        var x_dir = 1;
        if (e.preventDefault) {
            e.preventDefault();
        }
        if (e.clientX < this.start_x) {
            x_dir = -1;
        }
        var y_dir = 1;
        if (e.clientY < this.start_y) {
            y_dir = -1;
        }
        this.start_x = -1;
        this.start_y = -1;

        // 获取拖拽方向配置
        var dragDir = 1;
        // righttop
        if (x_dir > 0 && y_dir < 0) {
            dragDir = dragConfig.righttop;
        }
        // rightbottom
        else if (x_dir > 0 && y_dir > 0) {
            dragDir = dragConfig.rightbottom;
        }
        // lefttop
        else if (x_dir < 0 && y_dir < 0) {
            dragDir = dragConfig.lefttop;
        }
        // leftbottom
        else if (x_dir < 0 && y_dir > 0) {
            dragDir = dragConfig.leftbottom;
        }

        if (this.drag_selection.data) {
            chrome.extension.connect().postMessage({
                type: "superdrag",
                selection: this.drag_selection,
                x_dir: x_dir,
                y_dir: y_dir,
                dir: dragDir
            });
            return false;
        }
        return true;
    },

    dragEnd: function (e) {
        this.in_drag = false;
    }
};

// 通知BG页面加载配置
chrome.runtime.sendMessage({ type: "reloadconf" }, function (response) { });
// 加载配置
updateConfig();